import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:math' as math;
import 'dart:async';
import 'dart:ui' as ui;
import 'dart:typed_data';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_editor/image_editor.dart';

class ImageEditorPage extends StatefulWidget {
  final File imageFile;

  const ImageEditorPage({Key? key, required this.imageFile}) : super(key: key);

  @override
  _ImageEditorPageState createState() => _ImageEditorPageState();
}

class _ImageEditorPageState extends State<ImageEditorPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late File _currentImage;
  double _brightness = 0.0;
  double _contrast = 1.0;
  double _rotation = 0.0;
  double _scale = 1.0;
  bool _isFlipped = false;

  @override
  void initState() {
    super.initState();
    _currentImage = widget.imageFile;
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  // 背景消除
  Future<void> _removeBackground() async {
    if (!mounted) return;

    late BuildContext dialogContext;
    try {
      // 显示加载对话框
      await showDialog<void>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          dialogContext = context;
          return WillPopScope(
            onWillPop: () async => false,
            child: const Center(child: CircularProgressIndicator()),
          );
        },
      );

      if (!mounted) return;

      // 读取图片数据并转换为Uint8List
      final Uint8List imageBytes = Uint8List.fromList(
        await _currentImage.readAsBytes(),
      );

      // 创建图像编辑选项
      final ImageEditorOption option = ImageEditorOption();

      // 获取图片信息
      final Completer<ui.Image> completer = Completer();
      ui.decodeImageFromList(imageBytes, (ui.Image image) {
        completer.complete(image);
      });
      final ui.Image image = await completer.future;
      final int width = image.width;
      final int height = image.height;

      // 使用更优化的参数来处理背景
      // option.addOption(
      //   EditOption.colorMatrix([
      //     1.3, 0, 0, 0, 0, // 增强红色通道
      //     0, 1.3, 0, 0, 0, // 增强绿色通道
      //     0, 0, 1.3, 0, 0, // 增强蓝色通道
      //     0, 0, 0, 2, -0.5, // 调整透明度
      //   ]),
      // );

      // // 增加对比度以突出主体
      // option.addOption(ContrastOption(1.8));

      // // 调整亮度使图片更清晰
      // option.addOption(BrightnessOption(0.15));

      // // 使用叠加混合模式增强效果
      // option.addOption(
      //   MixOption(
      //     x: 0,
      //     y: 0,
      //     width: width,
      //     height: height,
      //     blendMode: BlendMode.overlay,
      //   ),
      // );

      // 处理图片
      final Uint8List? result = await ImageEditor.editImage(
        image: Uint8List.fromList(imageBytes),
        imageEditorOption: option,
      );

      if (!mounted) return;

      if (result != null && result.isNotEmpty) {
        // 创建临时文件保存处理后的图片
        final Directory tempDir = await Directory.systemTemp.createTemp();
        final File tempFile = File('${tempDir.path}/temp_image.png');
        await tempFile.writeAsBytes(result);

        setState(() {
          _currentImage = tempFile;
        });

        // 显示成功提示
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('背景消除完成')));
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('图片处理失败，请重试')));
      }
    } catch (e) {
      if (mounted) {
        print('背景消除时出错: $e');
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('背景消除失败，请重试')));
      }
    } finally {
      // 确保加载对话框被关闭
      if (mounted && Navigator.canPop(context)) {
        Navigator.pop(context);
      }
    }
  }

  // 剪裁图片
  Future<void> _cropImage() async {
    final croppedFile = await ImageCropper().cropImage(
      sourcePath: _currentImage.path,
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: '图片剪裁',
          toolbarColor: Colors.deepOrange,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.original,
          lockAspectRatio: false,
          aspectRatioPresets: [
            CropAspectRatioPreset.square,
            CropAspectRatioPreset.ratio3x2,
            CropAspectRatioPreset.original,
            CropAspectRatioPreset.ratio4x3,
            CropAspectRatioPreset.ratio16x9,
          ],
        ),
        IOSUiSettings(
          title: '图片剪裁',
          aspectRatioLockEnabled: false,
          aspectRatioPresets: [
            CropAspectRatioPreset.square,
            CropAspectRatioPreset.ratio3x2,
            CropAspectRatioPreset.original,
            CropAspectRatioPreset.ratio4x3,
            CropAspectRatioPreset.ratio16x9,
          ],
        ),
      ],
    );

    if (croppedFile != null) {
      setState(() {
        _currentImage = File(croppedFile.path);
      });
    }
  }

  // 调整亮度
  void _adjustBrightness(double value) {
    setState(() {
      _brightness = value;
    });
  }

  // 调整对比度
  void _adjustContrast(double value) {
    setState(() {
      _contrast = value;
    });
  }

  // 旋转图片
  void _rotate() {
    setState(() {
      _rotation += math.pi / 2;
    });
  }

  // 缩放图片
  void _adjustScale(double value) {
    setState(() {
      _scale = value;
    });
  }

  // 翻转图片
  void _flip() {
    setState(() {
      _isFlipped = !_isFlipped;
    });
  }

  Widget _buildBasicAdjustments() {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildToolButton(
                      icon: Icons.crop,
                      label: '剪裁',
                      onPressed: _cropImage,
                    ),
                    _buildToolButton(
                      icon: Icons.remove_circle_outline,
                      label: '消除背景',
                      onPressed: _removeBackground,
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                _buildSlider(
                  label: '亮度',
                  value: _brightness,
                  min: -1.0,
                  max: 1.0,
                  onChanged: _adjustBrightness,
                ),
                _buildSlider(
                  label: '对比度',
                  value: _contrast,
                  min: 0.0,
                  max: 2.0,
                  onChanged: _adjustContrast,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTransformations() {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildToolButton(
                      icon: Icons.rotate_90_degrees_ccw,
                      label: '旋转',
                      onPressed: _rotate,
                    ),
                    _buildToolButton(
                      icon: Icons.flip,
                      label: '翻转',
                      onPressed: _flip,
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                _buildSlider(
                  label: '缩放',
                  value: _scale,
                  min: 0.5,
                  max: 2.0,
                  onChanged: _adjustScale,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildToolButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
  }) {
    return Column(
      children: [
        IconButton(icon: Icon(icon), onPressed: onPressed),
        Text(label),
      ],
    );
  }

  Widget _buildSlider({
    required String label,
    required double value,
    required double min,
    required double max,
    required ValueChanged<double> onChanged,
  }) {
    return Column(
      children: [
        Text(label),
        Slider(value: value, min: min, max: max, onChanged: onChanged),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('图片编辑'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [Tab(text: '基础'), Tab(text: '变换')],
        ),
      ),
      body: Column(
        children: [
          Expanded(
            flex: 2,
            child: Center(
              child: Transform.scale(
                scale: _scale,
                child: Transform.rotate(
                  angle: _rotation,
                  child: Transform.scale(
                    scaleX: _isFlipped ? -1 : 1,
                    child: ColorFiltered(
                      colorFilter: ColorFilter.matrix([
                        _contrast,
                        0,
                        0,
                        0,
                        _brightness * 255,
                        0,
                        _contrast,
                        0,
                        0,
                        _brightness * 255,
                        0,
                        0,
                        _contrast,
                        0,
                        _brightness * 255,
                        0,
                        0,
                        0,
                        1,
                        0,
                      ]),
                      child: Image.file(_currentImage),
                    ),
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: TabBarView(
              controller: _tabController,
              children: [_buildBasicAdjustments(), _buildTransformations()],
            ),
          ),
        ],
      ),
    );
  }
}
